
<template>
  <div class="container">
    <el-dialog
      :title="
        compileDialog.dialogType === 'edit'
          ? '修改赠品入库单'
          : '创建赠品入库单'
      "
      :visible.sync="compileDialog.centerDialogVisible"
      width="90%"
      center
      :lock-scroll="true"
      append-to-body
      @opened="getData"
    >
      <div class="top">
        <el-select
          size="small"
          v-model="outer.value"
          :multiple="false"
          filterable
          remote
          reserve-keyword
          placeholder="请输入商品"
          :remote-method="remoteMethod"
          :loading="outer.loading"
          @change="getOptionGoods(outer.value)"
        >
          <el-option
            v-for="item in outer.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          class="add"
          size="small"
          type="primary"
          icon="el-icon-circle-plus"
          @click="addShopping"
          >添加商品</el-button
        >
        <label>调入方市场价：</label>
        <el-input-number
          size="small"
          :controls="false"
          v-model="to_market_value"
        ></el-input-number>
      </div>
      <el-table
        :data="formData"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="goods_name"
          label="商品"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="erp_goods_code"
          label="编号"
          width="90"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="purchase_num"
          label="毛重"
          align="center"
          width="100"
        ></el-table-column>

        <!-- <el-table-column label="仓库" align="center" width="200">
          <template slot-scope="scope">
            <el-select
              style="margin-bottom: 5px"
              v-model="entrepolists"
              :multiple="false"
              filterable
              remote
              center
              reserve-keyword
              placeholder="请选择仓库"
              :remote-method="entrepolistsMethod"
              :loading="entrepot.loading"
            >
              <el-option
                v-for="item in entrepot.option"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column> -->

        <el-table-column label="配送中心" align="center" width="200">
          <template slot-scope="scope">
            <el-select
              :multiple="false"
              filterable
              remote
              center
              reserve-keyword
              v-model="selectList"
              placeholder="请搜索选择配送中心"
              :remote-method="selectListsRemoteMethod"
              :loading="selectLists.loading"
            >
              <el-option
                v-for="item in selectLists.option"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="规格" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.spec"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="件数" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @blur="modification1(scope)"
              :controls="false"
              v-model="scope.row.qty"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="净单价" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @blur="unitPrice(scope)"
              :controls="false"
              v-model="scope.row.purchase_price"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="单皮重" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @blur="modification1(scope)"
              :controls="false"
              v-model="scope.row.tare"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="净重" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              @blur="suttle(scope)"
              size="small"
              :controls="false"
              v-model="scope.row.inp_num"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              @blur="totalPrices(scope)"
              v-model="scope.row.amount"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="备注" align="center" width="160">
          <template slot-scope="scope">
            <el-input type="textarea" v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleEdit(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button
        class="add"
        icon="el-icon-circle-plus"
        size="small"
        type="primary"
        @click="addExpenses_info"
        >添加配送方式</el-button
      >
      <el-table
        :data="expenses_info"
        border
        style="width: 50%"
        empty-text="暂无数据"
      >
        <el-table-column label="配送方式" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.options" placeholder="请选择配送方式">
              <el-option
                v-for="item in scope.row.select"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="配送价格" align="center">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.price"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-form
        ref="forms"
        label-width="150px"
        style="margin: 10px; width: 30%"
        label-position="left"
      >
        <el-form-item label="调货提成：">
          <el-input-number
            size="small"
            :controls="false"
            v-model="price"
            @blur="deduct(price)"
          ></el-input-number>
          <!-- <el-input style="width:200px" placeholder="请输入调货单价" v-model="price"></el-input> -->
        </el-form-item>
        <el-form-item label="采购员：">
          <el-select
            size="small"
            v-model="procurement.value"
            :multiple="false"
            filterable
            remote
            reserve-keyword
            placeholder="请输入采购员"
            :remote-method="insideProcurement"
            :loading="procurement.loading"
            @change="insidebuyer(procurement.value)"
          >
            <el-option
              v-for="item in procurement.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调货来源采购员：">
          <el-select
            v-model="procurements.value"
            :multiple="false"
            filterable
            remote
            reserve-keyword
            placeholder="请选择调货来源采购员"
            :remote-method="insideProcurements"
            :loading="procurements.loading"
          >
            <el-option
              v-for="item in procurements.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调货区域：">
          <el-select
            v-model="area.value"
            :multiple="false"
            filterable
            remote
            reserve-keyword
            placeholder="请选择调货区域编码/名称"
            :remote-method="insideArea"
            :loading="area.loading"
            @change="areabuyer(area.value)"
          >
            <el-option
              v-for="item in area.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input type="textarea" v-model="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { supplierList } from "@/api/supplier/supplierList";
import { commodityList } from "@/api/commodity/commodityList";
import { selectChooseWarehouse } from "@/api/warehouse/warehouse";
import { selectRdcData } from "@/api/select/select";
import {
  addPutStotage,
  editStorageBill,
  particularsStotage,
  getList,
  getOrgAreaList,
} from "@/api/putStorage/giftPutStotageList";

export default {
  props: {
    compileDialog: Object,
  },
  data() {
    return {
      formData: [],
      rules: {
        num1: [{ required: true, message: "填写角色名称", trigger: "blur" }],
        num2: [{ required: true, message: "填写描述", trigger: "blur" }],
      },
      commodityList: [],
      expenses_info: [],
      procurementList: [],
      areaList: [],
      to_market_value: 0,
      buyer: {
        name: "",
        code: "",
      },
      areaCenter: {
        name: "",
        code: "",
      },
      price: "",
      textarea: "",
      outer: {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      },
      inside: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
        buy_order_id: "",
      },
      procurement: {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      },
      procurements: {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      },
      area: {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      },
      entrepolists: "",
      entrepot: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      selectLists: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      selectList: "",
      search: {
        selectnamecode: "",
        housenamecode: "",
      },
    };
  },
  created() {},
  methods: {
    //获取修改数据
    getData() {
      let data = {
        page: 1,
        limit: 50,
      };
      if (this.compileDialog.dialogType == "edit") {
        this.formData = [];
        let data = {
          id: this.compileDialog.id,
        };
        particularsStotage(data).then((data) => {
          this.expenses_info = [];
          if (data.code == 0) {
            data.data.info.expenses_info.forEach((res) => {
              this.expenses_info.push({
                select: [
                  {
                    label: "运费",
                    value: 1,
                  },
                  {
                    label: "其他费用",
                    value: 2,
                  },
                ],
                price: res.expenses,
                options: res.type == 1 ? "运费" : "其他费用",
              });
            });
            this.entrepolists = '';
            this.selectList = data.data.info.rdc_code;
            this.entrepot.label = data.data.info.warehouse_name;
            this.selectLists.label = data.data.info.rdc_name;
            this.textarea = data.data.info.exp_remark;
            this.formData.push(data.data.info);
            this.buyer.name = data.data.info.buyer;
            this.buyer.code = data.data.info.buyer_code;
            this.procurement.value = data.data.info.buyer;
            this.sum = data.data.info.inp_goods_num;
            this.sum1 = data.data.info.tare;
            this.inside.id = data.data.info.supplier_id;
            this.price = data.data.info.allocateprice;
            this.areaCenter.name = data.data.info.allocateareaname;
            this.areaCenter.code = data.data.info.allocateareacode;
            this.procurements.value = data.data.info.allocatebuyer;
            this.to_market_value = data.data.info.to_market_value;

            this.area.value =
              data.data.info.allocateareaname != ""
                ? data.data.info.allocateareaname +
                  "/" +
                  data.data.info.allocateareacode
                : "";
            this.getDatas();
          }
        });
      } else {
        this.formData = [];
        this.inside.id = "";
        this.inside.value = "";
      }
    },
    // 获取初始商品列表
    getDatas() {
      let data = {
        page: 1,
        limit: 50,
        supplier_id: this.inside.id,
      };
      commodityList(data).then((res) => {
        this.outer.options = res.data.data.map((item) => {
          return { value: `${item.code}`, label: `${item.name}` };
        });
        this.commodityList = res.data.data;
      });
      let datas = {
        key: "",
      };
      getList(datas).then((res) => {
        this.procurement.options = res.data.map((item) => {
          return { value: `${item.code}`, label: `${item.name}` };
        });
        this.procurements.options = res.data.map((item) => {
          return { value: `${item.name}`, label: `${item.name}` };
        });
        this.procurementList = res.data;
      });
      getOrgAreaList(datas).then((res) => {
        this.area.options = res.data.map((item) => {
          return { value: `${item.code}`, label: `${item.name}/${item.code}` };
        });
        this.areaList = res.data;
      });
      this.getselsetData();
      this.getoptionData();
    },
    getselsetData() {
      let data = {
        page: 1,
        limit: 500,
        code_or_name: this.search.selectnamecode,
      };
      //获取配送中心
      selectRdcData(data).then((res) => {
        if (res.data.paginate.data) {
          this.selectLists.option = res.data.paginate.data.map((item) => {
            return { value: `${item.d_code}`, label: `${item.d_name}` };
          });
        }
      });
    },
    getoptionData() {
      let data = {
        page: 1,
        limit: 500,
        name: this.search.housenamecode,
      };
      //获取仓库
      selectChooseWarehouse(data).then((res) => {
        if (res.data.data) {
          this.entrepot.option = res.data.data.map((item) => {
            return { value: `${item.house_code}`, label: `${item.house_name}` };
          });
        }
      });
    },

    // 获取仓库方法
    entrepolistsMethod(query) {
      if (query !== "") {
        this.getenterpolistList(query);
      } else {
        this.entrepot.options = [];
      }
    },
    //获取仓库数据
    getenterpolistList(query) {
      this.search.housenamecode = query;
      this.getoptionData();
    },
    // 嵌套搜索配送方式数据
    selectListsRemoteMethod(query) {
      if (query !== "") {
        this.houseList(query);
      } else {
        this.selectLists.option = [];
      }
    },
    //获取配送数据
    houseList(query) {
      this.search.selectnamecode = query;
      this.getselsetData();
    },
    //添加配送方式
    addExpenses_info() {
      this.expenses_info.push({
        select: [
          {
            label: "运费",
            value: 1,
          },
          {
            label: "其他费用",
            value: 2,
          },
        ],
        price: "",
        options: "",
      });
    },
    //删除配送方式
    handleDelete(scope) {
      this.expenses_info.splice(scope.$index, 1);
    },
    //获取采购员name和code
    insidebuyer(e) {
      let center = this.procurementList.filter((res) => {
        return res.code == e;
      });
      console.log(center, 66666);
      this.buyer = {
        name: center[0].name,
        code: center[0].code,
      };
    },
    areabuyer(e) {
      let center = this.areaList.filter((res) => {
        return res.code == e;
      });
      this.areaCenter = {
        name: center[0].name,
        code: center[0].code,
      };
    },
    getOptionGoods(val) {
      console.log(this.outer);
    },
    //获取采购员列表
    getProcurement(query) {
      let data = {
        key: query,
      };
      this.procurement.loading = true;
      getList(data).then((res) => {
        this.procurement.list = res.data.map((item) => {
          return { value: `${item.code}`, label: `${item.name}` };
        });
        this.procurement.loading = false;
        this.procurement.options = this.procurement.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.procurementList = res.data;
      });
    },
    //获取调货采购员列表
    getProcurements(query) {
      let data = {
        key: query,
      };
      this.procurements.loading = true;
      getList(data).then((res) => {
        this.procurements.list = res.data.map((item) => {
          return { value: `${item.name}`, label: `${item.name}` };
        });
        this.procurements.loading = false;
        this.procurements.options = this.procurements.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      });
    },
    //获取区域列表
    areaMent(query) {
      let data = {
        key: query,
      };
      this.area.loading = true;
      getOrgAreaList(data).then((res) => {
        this.area.list = res.data.map((item) => {
          return { value: `${item.code}`, label: `${item.name}/${item.code}` };
        });
        this.area.loading = false;
        this.area.options = this.area.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.areaList = res.data;
      });
    },
    //获取商品列表
    getCommodityList(query) {
      let data = {
        search: query,
        page: 1,
        limit: 100,
        supplier_id: this.inside.id,
      };
      this.outer.loading = true;
      commodityList(data).then((res) => {
        this.outer.list = res.data.data.map((item) => {
          return { value: `${item.code}`, label: `${item.name}` };
        });
        this.outer.loading = false;
        this.outer.options = this.outer.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.commodityList = res.data.data;
      });
    },
    // 删除
    handleEdit(scope) {
      let code = scope.row.goods_erp_code;
      this.formData.forEach((res, index) => {
        if (res.goods_erp_code == code) {
          this.formData.splice(index, 1);
        }
      });
    },
    //修改件数和单皮重
    modification1(scope) {
      let objString = JSON.stringify(this.formData);
      let data = JSON.parse(objString);
      if (
        scope.row.qty != "" &&
        scope.row.qty != undefined &&
        scope.row.tare != "" &&
        scope.row.tare != undefined
      ) {
        data[0].purchase_num = (
          scope.row.qty * scope.row.tare +
          scope.row.inp_num
        ).toFixed(4);
      } else {
        data[0].purchase_num = scope.row.inp_num || 0;
      }
      this.formData = [];
      data.forEach((res) => {
        this.formData.push(res);
      });
    },
    //修改净重
    suttle(scope) {
      let objString = JSON.stringify(this.formData);
      let data = JSON.parse(objString);
      if (scope.row.inp_num != "" && scope.row.inp_num != undefined) {
        data[0].purchase_num = (
          scope.row.qty * scope.row.tare +
          scope.row.inp_num
        ).toFixed(4);
      } else {
        scope.row.inp_num = 0;
        data[0].purchase_num = (
          scope.row.qty * scope.row.tare +
          scope.row.inp_num
        ).toFixed(4);
      }
      if (
        scope.row.purchase_price != "" &&
        scope.row.purchase_price != undefined &&
        scope.row.inp_num != "" &&
        scope.row.inp_num != undefined
      ) {
        data[0].amount = (scope.row.purchase_price * scope.row.inp_num).toFixed(
          4
        );
      } else {
        data[0].amount = 0;
      }
      this.formData = [];
      data.forEach((res) => {
        this.formData.push(res);
      });
    },
    //修改净单价
    unitPrice(scope) {
      let objString = JSON.stringify(this.formData);
      let data = JSON.parse(objString);
      if (
        scope.row.purchase_price != "" &&
        scope.row.purchase_price != undefined &&
        scope.row.inp_num != "" &&
        scope.row.inp_num != undefined
      ) {
        data[0].amount = (scope.row.purchase_price * scope.row.inp_num).toFixed(
          4
        );
      } else {
        data[0].amount = 0;
      }
      this.formData = [];
      data.forEach((res) => {
        this.formData.push(res);
      });
    },
    //修改总价
    totalPrices(scope) {
      let objString = JSON.stringify(this.formData);
      let data = JSON.parse(objString);
      if (
        scope.row.amount != "" &&
        scope.row.amount != undefined &&
        scope.row.inp_num != "" &&
        scope.row.inp_num != undefined
      ) {
        data[0].purchase_price = (scope.row.amount / scope.row.inp_num).toFixed(
          4
        );
      } else {
        data[0].purchase_price = 0;
        data[0].inp_num = 0;
        data[0].amount = 0;
      }
      this.formData = [];
      data.forEach((res) => {
        this.formData.push(res);
      });
    },
    //提交
    confirm() {
      if (this.formData.length > 0) {
        console.log(66666666);
        if ( this.selectList) {
          console.log( this.selectList, 22222222);
        } else {
          this.$message({
            message: "请选择配送中心",
            type: "info",
          });
          return;
        }
        let arr = [];
        this.expenses_info.forEach((res) => {
          arr.push({ type: res.options, expenses: res.price });
        });
        let data = {
          id: this.compileDialog.id,
          type: 50,
          warehouse_code: '',
          rdc_code: this.selectList,
          expenses_info: JSON.stringify(arr),
          exp_remark: this.textarea,
          buyer: this.buyer.name,
          buyer_code: this.buyer.code,
          supplier_id: this.formData[0].supplier_id,
          goods_id: this.formData[0].goods_id,
          erp_goods_id: this.formData[0].erp_goods_id,
          erp_goods_code: this.formData[0].erp_goods_code,
          goods_name: this.formData[0].goods_name,
          purchase_num: this.formData[0].purchase_num,
          purchase_price: this.formData[0].purchase_price,
          unit: this.formData[0].unit,
          tare: this.formData[0].tare,
          qty: this.formData[0].qty,
          inp_num: this.formData[0].inp_num,
          spec: this.formData[0].spec,
          amount: this.formData[0].amount,
          allocateprice: this.price,
          to_market_value: this.to_market_value,
          allocateareacode: this.areaCenter.code,
          allocateareaname: this.areaCenter.name,
          allocatebuyer: this.procurements.value,
          remark: this.formData[0].remark,
        };
        console.log(data);
        // return;
        editStorageBill(data)
          .then((res) => {
            if (res.code == 0) {
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.hideDialog();
              this.$emit("upData");
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
            this.hideDialog();
            this.insideHideDialog();
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$message({
          message: "请添加商品",
          type: "info",
        });
      }
    },
    //调货
    deduct(val) {
      console.log(val);
      if (
        this.to_market_value == 0 ||
        this.formData.length == 0 ||
        this.formData[0].purchase_price == 0
      ) {
        this.price = 0;
      } else {
        let price = (
          (this.to_market_value - this.formData[0].purchase_price || 0) / 2
        ).toFixed(4);
        if (val > price) {
          this.price = 0;
        }
      }
    },
    // 显示嵌套层
    insideConfirm() {
      if (this.inside.id == "") {
        this.$message({
          message: "请选择供应商",
          type: "info",
        });
      } else {
        this.inside.innerVisible = true;
      }
    },
    //添加商品
    addShopping() {
      if (this.outer.value == "") {
        this.$message({
          message: "请选择商品",
          type: "info",
        });
      } else {
        if (this.formData.length > 0) {
          this.$message({
            message: "只能添加一个商品",
            type: "info",
          });
        } else {
          let commodity = this.commodityList.filter((res) => {
            return res.code == this.outer.value;
          });
          let goods = {
            goods_id: commodity[0].id,
            goods_erp_id: commodity[0].erp_id,
            goods_erp_code: commodity[0].code,
            goods_name: commodity[0].name,
            goods_num: 0,
            goods_price: 0,
            unit: commodity[0].unit,
            markup: 0,
            inp_goods_num: 0,
            inp_goods_price: 0,
            inp_markup: 0,
            tare: 0,
            qty: 0,
            weight: 0,
            spec: 0,
            amount: 0,
            remark: "",
          };
          this.formData.push(goods);
        }
      }
    },
    //搜索商品数据
    remoteMethod(query) {
      if (query !== "") {
        this.getCommodityList(query);
      } else {
        this.outer.options = [];
      }
    },
    //搜索采购员
    insideProcurement(query) {
      if (query !== "") {
        this.getProcurement(query);
      } else {
        this.procurement.options = [];
      }
    },
    //搜索调货采购员
    insideProcurements(query) {
      if (query !== "") {
        this.getProcurements(query);
      } else {
        this.procurements.options = [];
      }
    },
    //搜索区域
    insideArea(query) {
      if (query !== "") {
        this.areaMent(query);
      } else {
        this.area.options = [];
      }
    },
    //取消
    cancel() {
      this.insideCancel();
    },

    //取消方法
    hideDialog() {
      this.inside.innerVisible = false;
    },
    // 嵌套取消
    insideCancel() {
      this.hideDialog();
      this.insideHideDialog();
    },
    // 嵌套取消方法
    insideHideDialog() {
      this.compileDialog.centerDialogVisible = false;
    },
  },
};
</script>
<style scoped>
.top {
  position: relative;
  /* height: 40px; */
}
.main {
  display: flex;
  justify-content: center;
}
.add {
  margin: 10px 0;
  margin-left: auto;
}
</style>